package com.yc.cloud.common.basic.annotation;

import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import java.text.ParseException;
import java.text.SimpleDateFormat;

public class DateValidator implements ConstraintValidator<ValidDate, String> {

    private String dateFormat;

    @Override
    public void initialize(ValidDate constraintAnnotation) {
        // 获取注解中的格式
        this.dateFormat = constraintAnnotation.format();
    }

    @Override
    public boolean isValid(String dateStr, ConstraintValidatorContext context) {
        if (dateStr == null || dateStr.trim().isEmpty()) {
            return true; // 由 @NotEmpty 处理
        }
        SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
        sdf.setLenient(false); // 设置为严格模式
        try {
            sdf.parse(dateStr);
            return true; // 日期格式正确
        } catch (ParseException e) {
            return false; // 日期格式不正确
        }
    }
}


